package com.sesame.mq.rabbit.config;

import lombok.extern.apachecommons.CommonsLog;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import java.text.MessageFormat;

@CommonsLog
@Component
public class RabbitConfig {


    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 此处为模版类定义 Jackson消息转换器
     * ConfirmCallback接口用于实现消息发送到RabbitMQ交换器后接收ack回调   即消息发送到exchange  ack
     * ReturnCallback接口用于实现消息发送到RabbitMQ 交换器，但无相应队列与交换器绑定时的回调  即消息发送不到任何一个队列中
     *
     * @return the amqp template
     */
    @Bean
    public AmqpTemplate amqpTemplate() {
        //消息转换器
//        rabbitTemplate.setMessageConverter(new Jackson2JsonMessageConverter());
        //编码
        rabbitTemplate.setEncoding("UTF-8");
        rabbitTemplate.setMandatory(true);
        //rabbitTemplate.setR
        //开启消息发送回调
        rabbitTemplate.setReturnCallback((message, replyCode, replyText, exchange, routingKey) -> {
            String correlationId = message.getMessageProperties().getCorrelationId();
            log.info(MessageFormat.format("消息：{0} 发送失败, 应答码：{1} 原因：{2} 交换机: {3}  路由键: {4}", correlationId, replyCode, replyText, exchange, routingKey));
        });
        // 开启消息确认回调
        rabbitTemplate.setConfirmCallback((correlationData, ack, cause) -> {
            if (ack) {
                log.info(MessageFormat.format("消息发送到exchange成功,id: {0}", correlationData));
            } else {
                log.info(MessageFormat.format("消息发送到exchange失败,原因: {0}", cause));
            }
        });
        return rabbitTemplate;
    }
}
